﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FlowersStore
{
	public class ProductPosition
	{
		public long ProductId;
		public int Quantity;
	}

	public class UserCart
	{
		List<ProductPosition> positions=new List<ProductPosition>();

		public List<ProductPosition> Positions
		{ get { return positions; } }

		public void AddPosition(long productId,int quantity)
		{
			var pos = (from p in positions
					   where p.ProductId == productId
					   select p).SingleOrDefault();
			if (pos == null)
				positions.Add(new ProductPosition { ProductId = productId, Quantity = quantity });
			else
				pos.Quantity += quantity;
		}

		public void DeletePosition(long productId, int quantity)
		{
			var pos = (from p in positions
					   where p.ProductId == productId
					   select p).SingleOrDefault();
			if (pos != null)
				if (pos.Quantity > quantity)
					pos.Quantity -= quantity;
				else
					positions.Remove(pos);
		}

		public void SetPositionQuantity(long productId, int quantity)
		{
			var pos = (from p in positions
					   where p.ProductId == productId
					   select p).SingleOrDefault();
			if (pos != null)
				if (pos.Quantity != quantity)
					pos.Quantity = quantity;				
		}

		public List<long> GetProductIds()
		{
			return (from p in positions
					select p.ProductId).ToList();
		}

		public int GetProductQuantity(long productId)
		{
			return (from pos in positions
					where pos.ProductId == productId
					select pos.Quantity).SingleOrDefault();
		}

		public decimal ComputeTotalPrice()
		{
			using (FlowerStoreDataContext db = new FlowerStoreDataContext())
			{
				
				decimal totalPrice = 0;
				foreach (ProductPosition pos in positions)
				{
					totalPrice += (from p in db.Products
								   where p.Product_id == pos.ProductId
								   select p.Product_price).Single() * pos.Quantity;
				}
				return totalPrice;
			}
		}

		public int GetProductsCount()
		{
			return (from pos in positions
					select pos.Quantity).Sum();
		}
	}
}